package com.novunda.platform.web;

import com.novunda.platform.common.exception.NovException;
import com.novunda.platform.common.reponse.QrCodeStatusResponse;
import com.novunda.platform.common.utils.GsonUtils;
import com.novunda.platform.common.utils.StringUtil;
import com.novunda.platform.common.utils.UserUtils;
import com.novunda.platform.common.web.controller.BaseController;
import com.novunda.platform.entities.User;
import com.novunda.platform.services.LogService;
import com.novunda.platform.services.LoginService;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录Controller
 *
 * @author linfeng
 * @since 2016/8/30
 */
@Controller
public class LoginController extends BaseController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private LogService logService;

    /**
     * 账号密码方式登录
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(HttpServletRequest request, HttpServletResponse response,
                        RedirectAttributes redirectAttributes, Model model) {
        User user = UserUtils.getUser();
        // 如果已经登录，则跳转到管理首页
        if (user.getId() != null) {
            redirectAttributes.addAttribute("redirectUri", request.getParameter("redirect_uri"));
            return "redirect:/";
        }
        model.addAttribute("redirectUri", request.getParameter("redirect_uri"));
        model.addAttribute("qrcode", loginService.getQRCode());
        return "tcalogin";
    }

    /**
     * 二维码方式登录
     */
    @RequestMapping(value = "/qrlogin")
    public String qrLogin(HttpServletRequest request, HttpServletResponse response,
                          RedirectAttributes redirectAttributes, Model model) {
        User user = UserUtils.getUser();
        // 如果已经登录，则跳转到管理首页
        if (user.getId() != null) {
            redirectAttributes.addAttribute("redirectUri", request.getParameter("redirect_uri"));
            return "redirect:/";
        }
        model.addAttribute("redirectUri", request.getParameter("redirect_uri"));
        model.addAttribute("qrcode", loginService.getQRCode());
        return "tcalogin";
    }

    /**
     * 登录失败，真正登录的POST请求由Filter完成
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(
            @RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String username,
            HttpServletRequest request, RedirectAttributes redirectAttributes, Model model) {
        User user = UserUtils.getUser();
        // 如果已经登录，则跳转到管理首页
        if (user.getId() != null) {
            redirectAttributes.addAttribute("redirectUri", request.getParameter("redirect_uri"));
            return "redirect:/";
        }
        model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, username);
        model.addAttribute("redirectUri", request.getParameter("redirect_uri"));
        return "redirect:/login";
    }

    @RequestMapping(value = {"/welcome", "/", "/index"}, method = RequestMethod.GET)
    public String index(Model model) {
        if (logService.warn()) {
            // 审计告警提示
            addMessage(model, "审计记录数量已达告警值，请及时清理!");
        }
        return "index";
    }

    @RequestMapping("/login/status")
    @ResponseBody
    public String getQRCodeStatus(String scode) {
        QrCodeStatusResponse statusResponse;
        if (StringUtil.isEmpty(scode)) {
            statusResponse = new QrCodeStatusResponse();
            statusResponse.setReturnCode(-1);
            statusResponse.setReturnMessage("inner error");
        } else {
            try {
                statusResponse = loginService.getQRCodeStatus(scode);
            } catch (NovException e) {
                LOG.error(e.getMessage());
                statusResponse = new QrCodeStatusResponse();
                statusResponse.setReturnCode(-1);
                statusResponse.setReturnMessage(e.getMessage());
            } catch (Exception e) {
                LOG.error(e.getMessage());
                statusResponse = new QrCodeStatusResponse();
                statusResponse.setReturnCode(-1);
                statusResponse.setReturnMessage("inner error");
            }
        }
        statusResponse.setType("login");
        return GsonUtils.getInstance().toJson(statusResponse);
    }

}
